package com.atao.baokede.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.atao.baokede.mapper.ItemMapper;
import com.atao.baokede.mapper.ItemOrderDetailMapper;
import com.atao.baokede.mapper.ItemOrderMapper;
import com.atao.baokede.mapper.MerchantMapper;
import com.atao.baokede.pojo.*;
import com.atao.baokede.pojo.dto.MerchantDto;
import com.atao.baokede.pojo.dto.MerchantDto2;
import com.atao.baokede.pojo.vo.MerchantVo;
import com.atao.baokede.service.FileService;
import com.atao.baokede.service.ItemOrderService;
import com.atao.baokede.service.ItemService;
import com.atao.baokede.service.MerchantService;
import com.atao.baokede.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MerchantServiceImpl implements MerchantService {
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private ItemOrderDetailMapper ItemOrderDetailMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemOrderMapper itemOrderMapper;

    @Override
    public Merchant findByName(String name) {
        return merchantMapper.findByName(name);
    }

    @Override
    public void register(MerchantDto merchantDto, Long userId) {
        Merchant merchant = new Merchant();
        BeanUtil.copyProperties(merchantDto, merchant);
        merchant.setStatus(1);
        merchant.setCreater(userId);
        merchant.setBalance(new BigDecimal(0));
        merchantMapper.register(merchant);
    }

    @Override
    public MerchantVo getMerchantInfo() {
        Map<String, Object> map = ThreadLocalUtil.getMerchant();
        Long merchantId = ((Number) map.get("id")).longValue();
        Merchant m = merchantMapper.getMerchantInfo(merchantId);
        return BeanUtil.copyProperties(m, MerchantVo.class);
    }

    @Override
    public void update(MerchantDto2 merchantDto2) {
        Map<String, Object> map = ThreadLocalUtil.getMerchant();
        Long merMerchantId = ((Number) map.get("id")).longValue();
        merchantMapper.update(merchantDto2, merMerchantId);
    }

    @Override
    public void updateLogo(String avatarUrl) throws Exception {
        Map<String, Object> map = ThreadLocalUtil.getMerchant();
        Long merchantId = ((Number) map.get("id")).longValue();
        //如果商家原本就有logo，需要删除原来的logo
        String oldLogo = merchantMapper.getMerchantInfo(merchantId).getLogo();
        if (oldLogo != null && !oldLogo.isEmpty()) {
            fileService.deletePhoto(oldLogo);
        }
        merchantMapper.updateLogo(avatarUrl, merchantId);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.getMerchant();
        Long merchantId = ((Number) map.get("id")).longValue();
        merchantMapper.updatePwd(newPwd, merchantId);
    }

    @Override
    public Merchant findByUserId(Long userId) {
        return merchantMapper.findByUserId(userId);
    }
    @Override
    public PageBean<MerchantOrder> findOrders(Integer status, String orderId, String name, Integer pageNum, Integer pageSize) {
        // 获取当前商家信息
        Map<String, Object> map = ThreadLocalUtil.getMerchant();
        Long merchantId = ((Number) map.get("id")).longValue();

        // 使用 PageHelper 进行分页
        PageHelper.startPage(pageNum, pageSize);

        // 根据商家ID查询订单详情相关数据（分页查询）
        List<DetailOrder> detailOrders = ItemOrderDetailMapper.findOrderIdsByMerchantId(merchantId, status, orderId, name);

        // 强转为 Page 对象以获取分页信息
        Page<DetailOrder> page = (Page<DetailOrder>) detailOrders;
        // 若无数据，直接返回空列表与总数
        if (detailOrders == null || detailOrders.isEmpty()) {
            PageBean<MerchantOrder> pb = new PageBean<>();
            pb.setTotal(page.getTotal());
            pb.setItems(new ArrayList<>());
            return pb;
        }

        // 根据 detailOrderIds 里的 order_id 去 order_header 表中查询 user_id 字段
        List<Long> orderIds = detailOrders.stream()
                .map(DetailOrder::getOrderId)
                .distinct()
                .toList();


        List<Map<String, Object>> userRows = itemOrderMapper.findUserIdsByOrderIds(orderIds);
        Map<Long, Long> userIdMap = new HashMap<>();
        if (userRows != null) {
            for (Map<String, Object> row : userRows) {
                if (row == null) continue;
                Object oid = row.get("order_id");
                Object uid = row.get("user_id");
                if (oid != null && uid != null) {
                    Long k = ((Number) oid).longValue();
                    Long v = ((Number) uid).longValue();
                    userIdMap.put(k, v);
                }
            }
        }

        // 根据 detailOrderIds 里的 item_id 去 item 表中查询 image 字段
        List<Long> itemIds = detailOrders.stream()
                .map(DetailOrder::getItemId)
                .distinct()
                .toList();

        List<Map<String, Object>> imageRows = itemMapper.findImagesByIds(itemIds);
        Map<Long, String> imageMap = new HashMap<>();
        if (imageRows != null) {
            for (Map<String, Object> row : imageRows) {
                if (row == null) continue;
                Object iid = row.get("id");
                Object img = row.get("image");
                if (iid != null) {
                    Long k = ((Number) iid).longValue();
                    String v = img == null ? "" : String.valueOf(img);
                    imageMap.put(k, v);
                }
            }
        }

        // 构造 MerchantOrder 列表
        List<MerchantOrder> merchantOrders = new ArrayList<>();
        for (DetailOrder detailOrder : detailOrders) {
            Long itemId = detailOrder.getItemId(); // 获取 item_id
            String image = imageMap.getOrDefault(itemId, ""); // 获取 image，默认值为空字符串

            Long orderId2 = detailOrder.getOrderId(); // 获取 order_id
            Long userId = userIdMap.getOrDefault(orderId2, -1L); // 获取 user_id，默认值为 -1L

            // 创建 MerchantOrder 对象并赋值
            MerchantOrder merchantOrder = new MerchantOrder();
            BeanUtil.copyProperties(detailOrder, merchantOrder);
            merchantOrder.setName(detailOrder.getItemName()); // 设置商品名称
            merchantOrder.setUserId(userId);
            merchantOrder.setImage(image);
            merchantOrder.setUpdateTime(detailOrder.getUpdateTime());
            // 添加到结果列表
            merchantOrders.add(merchantOrder);
        }

        // 构造分页结果对象
        PageBean<MerchantOrder> pb = new PageBean<>();
        pb.setTotal(page.getTotal()); // 设置总记录数
        pb.setItems(merchantOrders); // 设置当前页数据
        return pb;
    }

}
